package cdu.sl.controller;


import cdu.sl.common.Result;
import cdu.sl.dto.SavePermissionDTO;
import cdu.sl.dto.SaveRoleDTO;
import cdu.sl.entity.Permission;
import cdu.sl.entity.Role;
import cdu.sl.service.PermissionService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/permissions")
@RequiredArgsConstructor
@Slf4j
public class PermissionController {

    private final PermissionService permissionService;

    /**
     * 新增权限
     * @param savePermissionDTO 新增权限数据实体
     * @return 统一响应结果
     */
    @PostMapping
    @PreAuthorize("hasAuthority('PERMISSION_ADD')")
    public Result addRole(@RequestBody SavePermissionDTO savePermissionDTO) {
        log.info("新增权限:{}", savePermissionDTO);
        permissionService.add(savePermissionDTO);
        return Result.success();
    }


    /**
     * 修改权限
     * @param SavePermissionDTO 修改权限数据实体
     * @return 统一响应结果
     */
    @PreAuthorize("hasAuthority('PERMISSION_UPDATE')")
    @PutMapping
    public Result updateRole(@RequestBody SavePermissionDTO SavePermissionDTO) {
        log.info("修改权限：{}", SavePermissionDTO);
        permissionService.update(SavePermissionDTO);
        return Result.success();
    }


    /**
     * 删除权限
     * @param id 权限id
     * @return 统一响应结果
     */
    @PreAuthorize("hasAuthority('PERMISSION_DELETE')")
    @DeleteMapping("/{id}")
    public Result deleteRole(@PathVariable Integer id) {
        log.info("删除权限,权限id：{}", id);
        permissionService.delete(id);
        return Result.success();
    }

    /**
     * 获取所有权限信息
     * @return 所有权限信息
     */
    @PreAuthorize("hasAnyRole('ADMIN','USER','MANAGER')")
    @GetMapping("/list")
    public Result list() {
        log.info("获取所有权限信息");
        List<Permission> permissions = permissionService.findAll();
        return Result.success(permissions);
    }


    /**
     * 按照id查询权限信息
     * @param id 权限id
     * @return 权限信息
     */
    @PreAuthorize("hasAnyRole('ADMIN','USER','MANAGER')")
    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id) {
        log.info("获取权限信息：{}", id);
        Permission permission = permissionService.getById(id);
        return Result.success(permission);
    }




}
